import nonebot
from nonebot.adapters.qq import MessageEvent
from nonebot.params import CommandArg
from nonebot import on_command
from nonebot.rule import to_me
from httpx import AsyncClient, TimeoutException
from urllib.parse import quote
from bs4 import BeautifulSoup

# 创建命令处理器
search_drama = on_command("找广播剧", rule=to_me(), aliases={"搜广播剧", "广播剧", "找剧"}, priority=10, block=True)

@search_drama.handle()
async def handle_search(event: MessageEvent, args = CommandArg()):
    drama_name = args.extract_plain_text().strip()
    if not drama_name:
        await search_drama.finish("亦乐想帮你找广播剧哦~ 请告诉我剧名，例如：找广播剧 魔道祖师")

    await search_drama.send(f"🎧 亦乐正在努力寻找《{drama_name}》的广播剧...")

    result = await search_drama_website(drama_name)
    await search_drama.finish(result if result else f"亦乐没有找到《{drama_name}》相关的广播剧呢，换个名字试试看？")

async def search_drama_website(drama_name: str) -> str:
    """
    从 xdy.ksfuwu.com 搜索广播剧
    """
    # 构建搜索URL - 模拟网页搜索
    encoded_keyword = quote(drama_name)
    search_url = f"http://xdy.ksfuwu.com/?q={encoded_keyword}&page=1"
    
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate",
        "Connection": "keep-alive",
        "Upgrade-Insecure-Requests": "1"
    }

    try:
        async with AsyncClient(timeout=15.0) as client:
            response = await client.get(search_url, headers=headers)
            response.raise_for_status()
            
            # 解析HTML页面
            return parse_search_results(response.text, drama_name)
            
    except TimeoutException:
        nonebot.logger.error("搜索广播剧请求超时")
        return "搜索超时了，请稍后再试~"
    except Exception as e:
        nonebot.logger.error(f"搜索广播剧时出错: {e}")
        return "搜索过程中出错了，请稍后再试~"

def parse_search_results(html_content: str, drama_name: str) -> str:
    """
    解析搜索结果页面
    """
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 根据网站结构提取搜索结果
    result_items = soup.find_all('div', class_='resource-item')
    
    if not result_items:
        # 尝试其他可能的选择器
        result_items = soup.find_all('div', class_='item')
        result_items = result_items or soup.find_all('li', class_='result-item')
    
    if not result_items:
        return ""
    
    reply_msg = f"🎧 《{drama_name}》广播剧搜索结果：\n\n"
    
    for index, item in enumerate(result_items[:5], 1):
        try:
            # 提取标题
            title_elem = item.find('h3') or item.find('a') or item.find('div', class_='title')
            title = title_elem.get_text(strip=True) if title_elem else "未知标题"
            
            # 提取描述/信息
            desc_elem = item.find('p') or item.find('div', class_='desc') or item.find('span', class_='info')
            description = desc_elem.get_text(strip=True) if desc_elem else "暂无描述"
            
            # 提取链接
            link_elem = item.find('a')
            if link_elem and link_elem.get('href'):
                link = link_elem['href']
                if link.startswith('/'):
                    link = f"http://xdy.ksfuwu.com{link}"
            else:
                link = "暂无直接链接"
            
            reply_msg += f"{index}. {title}\n"
            reply_msg += f"   📝 {description[:50]}...\n"
            reply_msg += f"   🔗 查看详情: {link}\n\n"
            
        except Exception as e:
            nonebot.logger.warning(f"解析搜索结果项时出错: {e}")
            continue
    
    reply_msg += "💡 提示：请复制链接到浏览器查看详情，支持正版创作哦~"
    return reply_msg

# 帮助命令
drama_help = on_command("广播剧帮助", rule=to_me(), priority=5, block=True)

@drama_help.handle()
async def handle_help(event: MessageEvent):
    help_text = """
🎧 亦乐广播剧搜索帮助：

@亦乐 找广播剧 [剧名]  - 搜索广播剧资源
@亦乐 广播剧帮助      - 显示帮助信息

例如：
@亦乐 找广播剧 魔道祖师
@亦乐 找广播剧 将进酒

💡 提示：如果搜不到可以尝试简化的关键词哦~
"""
    await drama_help.finish(help_text)